package project02.controller.gh;

import java.util.Calendar;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import project02.cool.Consts;
import project02.dao.DateDataDao;
import project02.model.DateData;
import project02.model.UserInfo;

public class RegGtwController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(RegGtwController.class.getName());

    private DateDataDao dao = new DateDataDao();

    @Override
    public Navigation run() {

        UserInfo user = sessionScope("userInfo");

        if (!user.getPassword().equals(asString("userPass"))) {
            requestScope("result", "<script type=\"text/javascript\"> window.alert('パスワードが一致しません.'); </script>");
            return forward("../");
        }

        String dataId = user.getUserId() + String.format("%04d", asInteger("startYear")) + String.format("%02d", asInteger("startMonth")) + String.format("%02d", asInteger("startDate")) + String.format("%02d", asInteger("startHour"));

        Calendar calGtw = Calendar.getInstance();
        Calendar calGh = Calendar.getInstance();
        calGtw.set(Integer.parseInt(asString("startYear")), Integer.parseInt(asString("startMonth")) - 1, Integer.parseInt(asString("startDate")), Integer.parseInt(asString("startHour")), Integer.parseInt(asString("startMinuts")));
        calGh.set(Integer.parseInt(asString("endYear")), Integer.parseInt(asString("endMonth")) - 1, Integer.parseInt(asString("endDate")), Integer.parseInt(asString("endHour")), Integer.parseInt(asString("endMinuts")));

        DateData entity = new DateData();
        entity.setDataId(dataId);
        entity.setUserId(user.getUserId());
        entity.setYear(String.format("%04d", asInteger("startYear")));
        entity.setMonth(String.format("%02d", asInteger("startMonth")));
        entity.setDate(String.format("%02d", asInteger("startDate")));
        entity.setGoToWork(calGtw.getTime());
        entity.setGtwFlg(Consts.revision);
        entity.setGoHome(calGh.getTime());
        entity.setGhFlg(Consts.original);

        try {
            dao.makePersistentInTx(entity);
        } catch (Exception e) {
            requestScope("result", "<script type=\"text/javascript\"> window.alert('退勤に失敗しました。" + e.getMessage() + "; </script>");
            return forward("../");
        }

        requestScope("result", "<script type=\"text/javascript\"> window.alert('退勤処理を完了しました.'); </script>");

        return forward("../");
    }
}
